from conf import CONFIG
from webutils.layers.managers import HTTPAPIManager
from .. import const


class AccountAPI(HTTPAPIManager):
    base_url = CONFIG['API_ACCOUNT_BASE_URL']

    async def get_user_info(self, token):
        """获取用户信息
        """
        path = 'v1/oauth2/userinfo'
        params = {'token': token}
        async with self.do_request('GET', path, params=params) as resp_json:
            if resp_json.get('errcode') == 'invalid_token':
                return None
            data = {'name': resp_json.get('name', '')}
            if 'uid' in resp_json:
                data['uid'] = resp_json['uid']
            else:
                data['client_id'] = resp_json['client_id']
                data['classroom_id'] = 'default_classroom_id'
                data['device_type'] = const.DeviceType.DEFAULT.value
                if resp_json.get('config'):
                    if resp_json['config'].get('device'):
                        data['classroom_id'] = \
                            resp_json['config']['device']['classroom_id']
                        data['device_type'] = \
                            resp_json['config']['device']['device_type']
            return data


class NDSAPI(HTTPAPIManager):
    base_url = CONFIG['API_NDS_BASE_URL']

    async def get_unit_info(self, unit_id):
        """获取单元信息
        """
        path = f'/v1/units/{unit_id}/get'
        async with self.do_request('GET', path, use_cache=False) as resp_json:
            return resp_json

    async def get_user_role_of_course(self, token, course_id, user_id):
        """获取用户在指定课程中的身份
        """
        path = f'v1/courses/{course_id}/users/{user_id}/detail'
        params = {'token': token}
        async with self.do_request('GET', path, params=params) as resp_json:
            return resp_json['data']['identity']

    async def get_user_role_of_unit(self, token, unit_id, user_id):
        """获取用户在指定活动中的身份
        """
        path = f'v1/units/{unit_id}/users/{user_id}/detail'
        params = {'token': token}
        async with self.do_request('GET', path, params=params) as resp_json:
            return resp_json['data']['identity']
